class Translator {
    count = 0;
    constructor(api, text, callback ,error) {
        this.protocol = "http"
        this.api = api;
        this.target = this.protocol + "://" + this.api;

        this.text = text;
        this.id = -1;

        this.response = null;
        this.callback = callback; // 把翻译好的数据扔哪里去
        this.error = error || this.defualt_error;
        
    }
    run() {
        this.id = 114514;
        let req = new XMLHttpRequest();
        req.open("POST", this.target + "/task/new/", true);
        req.setRequestHeader("Content-Type", "application/json");
        let t = this;
        req.onreadystatechange = function() {
            if (req.readyState === 4 && req.status === 200) {
                let response = t.response = JSON.parse(req.responseText);
                if (response.code === 200 && response.msg === "success") {
                    // 创建任务成功, 开始定时查询
                    t.checkResult(t);
                } else {
                    t.error("create_fail");
                }
            }
        }
        req.send(JSON.stringify({
            text: this.text,
            id: this.id
        }))
    }
    checkResult(t) {
        let req = new XMLHttpRequest();
        req.open("GET", t.target + "/task/"+String(t.id)+"/", true);
        let f = t.checkResult;
        req.onreadystatechange = function() {
          if (req.readyState === 4 && req.status === 200) {
            var response = JSON.parse(req.responseText);
            if (response.code === 200 && response.status === "end") {
              // 翻译任务已完成，获取翻译结果
              t.callback(response.data);
            } else if (response.code === 200 && response.status === "running") {
              // 翻译任务还在进行中，继续定时查询翻译结果
              console.log("continue");
              setTimeout(() => {
                f(t);
              }, 1000); // 每隔1秒查询一次
            } else if (response.code === 200 && response.status === "error") {
                //服务器出错
                t.error("server_error");
            } else {
              console.error("Failed to check translation task result:", response.message);
            }
          }
        };
        req.send();
    }
    defualt_error(type) {
        console.log(this.response,type);
    }
}

export {
    Translator
}